package com.mycity.services;

import java.util.ArrayList;
import java.util.List;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;







import com.amazonaws.util.json.JSONArray;
import com.amazonaws.util.json.JSONException;
import com.amazonaws.util.json.JSONObject;
import com.mycity.bean.Post;
import com.mycity.dao.PostDao;
import com.mycity.util.Constants;

public class LocationService {

	public String client = "client_id="+Constants.INSTAGRAM_CLIENT_ID;

	PostDao postDao = new PostDao();

	public List<Post> nearbyPosts(double latitude, double longitude) throws IOException, JSONException{
		String url = "https://api.instagram.com/v1/locations/search?lat="+latitude+"&lng="+longitude+"&"+client;

		List<Post> postList = new ArrayList<Post>();

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();


		int responseCode = con.getResponseCode();

		if(responseCode==200){
			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			JSONObject json = new JSONObject(response.toString());
			JSONArray jarray = json.getJSONArray("data");

			for (int i = 0; i < jarray.length(); ++i) {
				JSONObject location= jarray.getJSONObject(i);
				int locationId = location.getInt("id");
				postList.addAll(postDao.getPostsByLocation(locationId));
			}
		}
		return postList;

	}

	public double[] findLatLng(int locationId) throws IOException, JSONException{
		String url = "https://api.instagram.com/v1/locations/"+locationId+"?"+client;

		double params[] = new double[2];
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();


		int responseCode = con.getResponseCode();

		if(responseCode == 200){
			BufferedReader in = new BufferedReader(
					new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();

			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();

			JSONObject json = new JSONObject(response.toString());
			JSONObject data = json.getJSONObject("data");

			params[0] = data.getDouble("latitude");
			params[1] = data.getDouble("longitude");
		}
		return params;

	}
}
